//
//  NSObject+UpdateVersion.m
//  UIColor+Extention
//
//  Created by YiXuePxh on 16/2/2.
//  Copyright © 2016年 上海益学. All rights reserved.
//

#import "NSObject+UpdateVersion.h"

@implementation NSObject (UpdateVersion)
+(NSMutableDictionary* )updateVersion{
    NSMutableDictionary* returnDict = [NSMutableDictionary dictionary];
    //获取当前版本号
    NSDictionary* infoDict = [[NSBundle mainBundle]infoDictionary];
    NSString* currentVersion = [infoDict objectForKey:@"CFBundleShortVersionString"];
    //请求iTunes数据  获取版本号  id参数为对应的应用appId
    NSString* url = @"http://itunes.apple.com/lookup?id=989677611";
    NSMutableURLRequest* request = [[NSMutableURLRequest alloc]init];
    [request setURL:[NSURL URLWithString:url]];
    [request setHTTPMethod:@"POST"];
    NSHTTPURLResponse* urlReponse = nil;
    NSError* err= nil;
    NSData* recervedData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlReponse error:&err];
    id resultJson = [NSJSONSerialization JSONObjectWithData:recervedData options:0 error:nil];
    NSArray* infoArray = [resultJson objectForKey:@"results"];
    BOOL index = false;
    if ([infoArray count]) {
        NSDictionary* releaseInfo = [infoArray firstObject];
        NSString* lastVersion = [releaseInfo objectForKey:@"version"];
        NSString* trackViewUrl = [releaseInfo objectForKey:@"trackViewUrl"];
        NSString* trackName = [releaseInfo objectForKey:@"trackName"];
        int doubleCurrentVersion = [[self cutOffStringWithPoint:currentVersion] intValue];
        int doubleLastVersion = [[self cutOffStringWithPoint:lastVersion] intValue];
        if (doubleCurrentVersion < doubleLastVersion) {
            index = true;    //  需要跟新
        }else{
            index = false;    //最新版本
        }
        [returnDict setObject:trackViewUrl forKey:@"trackViewUrl"];
        [returnDict setObject:trackName forKey:@"trackName"];
        [returnDict setObject:lastVersion forKey:@"version"];
    }
    NSString* boolIndex = [NSString stringWithFormat:@"%d",index];
    [returnDict setObject:boolIndex forKey:@"result"];
    return returnDict;
}
+(NSString* )cutOffStringWithPoint:(NSString* )str{
    NSArray* array = [str componentsSeparatedByString:@"."];
    NSString* returnStr = @"";
    for (NSString* string in array) {
        returnStr = [returnStr stringByAppendingString:string];
    }
    return returnStr;
}
@end
